/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.ventas;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.HTML;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import dp1.titandevelop.titano.persistent.DetalleDocumentoVenta;
import dp1.titandevelop.titano.persistent.Distribuidor;
import dp1.titandevelop.titano.persistent.DocumentoVenta;
import dp1.titandevelop.titano.persistent.Parametro;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.service.DistribuidorService;
import dp1.titandevelop.titano.service.DocumentoVentaService;
import dp1.titandevelop.titano.service.ParametroService;
import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author heli
 */
public class reporte_venta {

    private static Font fontBold = new Font(Font.FontFamily.COURIER, 12, Font.BOLD);
    private static Font fontNormal = new Font(Font.FontFamily.COURIER, 11, Font.NORMAL);
    private String nomArch;

    public reporte_venta(Date fechaIni, Date fechaFin, String nombreArchivo) throws Exception {

        String formattedDateIni = new SimpleDateFormat("dd/MM/yyyy").format(fechaIni);
        String formattedDateFin = new SimpleDateFormat("dd/MM/yyyy").format(fechaFin);
        this.nomArch = nombreArchivo;
        Document document = new Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(document,
                //new FileOutputStream("/tmp/reporte-venta.pdf"));
                new FileOutputStream(nombreArchivo));
        document.open();

        document.add(getHeader("Reporte de Ventas  "));

        document.add(getInformation(" "));

        Image image1 = Image.getInstance(getClass().getResource("/img/GOOD_COOKIE.jpg"));
        PdfPTable table4 = new PdfPTable(1); // Code 1
        PdfPCell cell001y = new PdfPCell(image1);
        cell001y.setBorder(0);
        table4.addCell(cell001y);

        document.add(table4);
        document.add(getInformation(" "));


        DistribuidorService service1 = new DistribuidorService();
        DocumentoVentaService service2 = new DocumentoVentaService();
        List<Producto> productos = service2.listProduct();
        Integer numProd = productos.size();


        List<Distribuidor> distribuidores = service1.listDistribuidor();



        //calculo la cantidad de productos + 1
        for (int i = 0; i < distribuidores.size(); i++) {
            List<DocumentoVenta> ventas = new ArrayList<DocumentoVenta>();
            ventas = service2.listVentaDistribuidor(distribuidores.get(i).getIddistribuidor(), fechaIni, fechaFin);

            PdfPTable table = new PdfPTable((numProd + 4)); // Code 1

            PdfPCell cell = new PdfPCell(new Paragraph(dataTable(distribuidores.get(i).getRazonsocial() + " - Periodo (" + formattedDateIni + " - " + formattedDateFin + ")")));
            cell.setColspan((numProd + 4));
            cell.setBorder(0);
            table.addCell(cell);

            PdfPCell cell01 = new PdfPCell(new Paragraph(cabeceraTable("Fecha")));
            table.addCell(cell01);
            for (int j = 0; j < productos.size(); j++) {
                PdfPCell cell02 = new PdfPCell(new Paragraph(cabeceraTable(productos.get(j).getDescripcion())));
                table.addCell(cell02);
            }
            PdfPCell cell03 = new PdfPCell(new Paragraph(cabeceraTable("Sub-Total")));
            table.addCell(cell03);

            PdfPCell cell04 = new PdfPCell(new Paragraph(cabeceraTable("IGV")));
            table.addCell(cell04);

            PdfPCell cell05 = new PdfPCell(new Paragraph(cabeceraTable("Total")));
            table.addCell(cell05);

            // hasta aqui la cabecera
            if (!ventas.isEmpty()) {

                for (int k = 0; k < ventas.size(); k++) {
                    String formattedDateEmision = new SimpleDateFormat("dd/MM/yyyy").format(ventas.get(k).getFechafacturacion());
                    table.addCell(celda("" + formattedDateEmision));
                    for (int m = 0; m < productos.size(); m++) {
                        Integer cantidad = 0;
                        List<DetalleDocumentoVenta> detalle = new ArrayList<DetalleDocumentoVenta>();
                        detalle = ventas.get(k).getDetalleDocumentoVentaArray();
                        for (int n = 0; n < detalle.size(); n++) {
                            if (detalle.get(n).getToProducto().getIdproducto() == productos.get(m).getIdproducto()) {
                                cantidad = detalle.get(n).getCantidad();

                            }
                        }
                        table.addCell(celda("" + cantidad));

                    }
                    table.addCell(celda("S/." + ventas.get(k).getMontototal()));
                    table.addCell(celda("S/." + ventas.get(k).getIgv()));
                    table.addCell(celda("S/." + ventas.get(k).getTotal()));
                }
            }

            document.add(table);
            document.add(getInformation(" "));
        }

/// aqui empiezan las boletas
        
        
            PdfPTable table = new PdfPTable((numProd + 4)); // Code 1

            PdfPCell cell = new PdfPCell(new Paragraph(dataTable("Boletas")));
            cell.setColspan((numProd + 4));
            cell.setBorder(0);
            table.addCell(cell);

            PdfPCell cell01 = new PdfPCell(new Paragraph(cabeceraTable("Fecha")));
            table.addCell(cell01);
            for (int j = 0; j < productos.size(); j++) {
                PdfPCell cell02 = new PdfPCell(new Paragraph(cabeceraTable(productos.get(j).getDescripcion())));
                table.addCell(cell02);
            }
            PdfPCell cell03 = new PdfPCell(new Paragraph(cabeceraTable("Sub-Total")));
            table.addCell(cell03);

            PdfPCell cell04 = new PdfPCell(new Paragraph(cabeceraTable("IGV")));
            table.addCell(cell04);

            PdfPCell cell05 = new PdfPCell(new Paragraph(cabeceraTable("Total")));
            table.addCell(cell05);

            List<DocumentoVenta> ventas = new ArrayList<DocumentoVenta>();
            ventas = service2.listVentaBoleta(fechaIni, fechaFin);
            
            // hasta aqui la cabecera
            if (!ventas.isEmpty()) {

                for (int k = 0; k < ventas.size(); k++) {
                    String formattedDateEmision = new SimpleDateFormat("dd/MM/yyyy").format(ventas.get(k).getFechafacturacion());
                    table.addCell(celda("" + formattedDateEmision));
                    for (int m = 0; m < productos.size(); m++) {
                        Integer cantidad = 0;
                        List<DetalleDocumentoVenta> detalle = new ArrayList<DetalleDocumentoVenta>();
                        detalle = ventas.get(k).getDetalleDocumentoVentaArray();
                        for (int n = 0; n < detalle.size(); n++) {
                            if (detalle.get(n).getToProducto().getIdproducto() == productos.get(m).getIdproducto()) {
                                cantidad = detalle.get(n).getCantidad();

                            }
                        }
                        table.addCell(celda("" + cantidad));

                    }
                    table.addCell(celda("S/." + ventas.get(k).getMontototal()));
                    table.addCell(celda("S/." + ventas.get(k).getIgv()));
                    table.addCell(celda("S/." + ventas.get(k).getTotal()));
                }
            }

            document.add(table);
            document.add(getInformation(" "));
        

        document.close();
        //imprimir();
    }

    private Chunk cabeceraTable(String cadena) {
        Chunk c = new Chunk(cadena);
        c.setFont(fontBold);
        c.getFont().setSize(10);
        c.getFont().setFamily("Arial");
        return c;
    }

    private Chunk dataTable(String cadena) {
        Chunk c = new Chunk(cadena);
        c.getFont().setSize(8);
        c.getFont().setFamily("Arial");
        return c;
    }

    private PdfPCell celda(String cadena) {

        PdfPCell cell = new PdfPCell(new Paragraph(dataTable(cadena)));
        return cell;
    }

    private Paragraph getHeader(String header) {
        Paragraph paragraph = new Paragraph();
        Chunk chunk = new Chunk();

        paragraph.setAlignment(Element.ALIGN_CENTER);
        chunk.append(header + getCurrentDateTime() + "\n");
        chunk.setFont(fontBold);
        chunk.getFont().setFamily("Arial");
        paragraph.add(chunk);
        return paragraph;
    }

    private Paragraph getInformation(String informacion) {
        Paragraph paragraph = new Paragraph();
        Chunk chunk = new Chunk();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        chunk.append(informacion);
        chunk.setFont(fontNormal);

        paragraph.add(chunk);
        return paragraph;
    }

    private Paragraph getInformation2(String informacion) {
        Paragraph paragraph = new Paragraph();
        Chunk chunk = new Chunk();
        paragraph.setAlignment(Element.ALIGN_LEFT);
        chunk.append(informacion);
        chunk.setFont(fontBold);
        //chunk.setFont(fontNormal);
        paragraph.add(chunk);
        return paragraph;
    }

    private Paragraph getInformationFooter(String informacion) {
        Paragraph paragraph = new Paragraph();
        Chunk chunk = new Chunk();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        chunk.append(informacion);
        chunk.setFont(new Font(Font.FontFamily.COURIER, 8, Font.NORMAL));
        paragraph.add(chunk);
        return paragraph;
    }

    private float getConvertCmsToPoints(float cm) {
        return cm * 28.4527559067f;
    }

    public void imprimir() {

        Desktop d = Desktop.getDesktop();
        try {
            if (Desktop.isDesktopSupported()) {
                //d.open(new File("/tmp/reporte-venta.pdf"));
                d.open(new File(this.nomArch));
                // d.print(new File("factura2.pdf"));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private String getCurrentDateTime() {
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yy '-' hh:mm");
        return ft.format(dNow);
    }

    public static void main(String[] args, Date fechaIni, Date fechaFin, String fileName) {
        try {
            reporte_venta pdfTable = new reporte_venta(fechaIni, fechaFin, fileName);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
